﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace FreedBack.Helpers
{
    public static class TwitterBootstrapHelperExtensions
    {
        public static MvcHtmlString BootstrapValidationSummary(this HtmlHelper helper,
                               bool excludePropertyErrors, bool showFindLink, string message)
        {
            if (helper.ViewData.ModelState.Values.All(v => v.Errors.Count == 0)) return new MvcHtmlString(string.Empty);

            var errorsList = new StringBuilder("<ul>");
            var hasNonPropertyErrors = false;

            foreach (var currKey in helper.ViewData.ModelState.Keys)
            {
                var currItem = helper.ViewData.ModelState[currKey];
                if (currItem.Errors.Any())
                {
                    foreach (var currError in currItem.Errors)
                    {
                        if (!string.IsNullOrWhiteSpace(currKey))
                        {
                            if (!excludePropertyErrors)
                            {
                                if (showFindLink)
                                {
                                    errorsList.Append(string.Format("<li>{0} <label for=\"{1}\" class=\"findLabel\">(find)</label></li>", currError.ErrorMessage, currKey));
                                }
                                else
                                {
                                    errorsList.Append(string.Format("<li>{0}</li>", currError.ErrorMessage));
                                }
                            }
                        }
                        else
                        {
                            errorsList.Append(string.Format("<li>{0}</li>", currError.ErrorMessage));
                            hasNonPropertyErrors = true;
                        }
                    }
                }
            }

            errorsList.Append("</ul>");
            if (excludePropertyErrors && !hasNonPropertyErrors)
            {
                return new MvcHtmlString(string.Empty);
            }

            return new MvcHtmlString(string.Format("<div class=\"alert-message block-message error\"><strong>{0}</strong>{1}</div>", message, errorsList.ToString()));
        }
    }
}